//
//  main.cpp
//  autoreleasePtr
//
//  Created by huge on 2021/7/23.
//  Copyright © 2021 huge. All rights reserved.
//

#include <iostream>
#include <memory>

#define autorelease

template <typename T>
class auto_release_ptr {
public:
    auto_release_ptr(T* t):_t(t){};
    ~auto_release_ptr()
    {
//        std::cout << "~auto_release_ptr!\n";

        delete _t;
    };
    
    T* getPtr()
    {
        return _t;
    }
    
private:
    T* _t;
};

class auto_delete_ptr{
public:
    auto_delete_ptr(int32_t* p):_t(p){};
    ~auto_delete_ptr(){
        delete _t;
    }
    int32_t* getPtr(){
        return _t;
    }
private:
    int32_t* _t;
};

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    
#ifdef autorelease
    std::cout << "auto release!\n";
    for (int i = 1; i<= 10000000; i++) {
        
        auto_delete_ptr p = new int32_t[3]; // in this condition no memory leakage
        auto_delete_ptr* pt = new auto_delete_ptr( new int32_t[3]);//this status will result in memory leakage
        
        int32_t* ptr = pt->getPtr();
        ptr[0] = 1;
        ptr[2] = 2;
        ptr[3] = 3;
        
        //        std::cout << "i: " << i <<std::endl;
    }
    
    
    //used memory size is 5.3M
    //for circulation's scope is every circulation, in other wise , every i is a scope, is a ptr's life time.
//    for (int i = 1; i<= 10000000; i++) {
//        auto arp = auto_release_ptr<int32_t>(new int32_t[3]);
//        int32_t* ptr = arp.getPtr();
//        ptr[0] = 1;
//        ptr[1] = 2;
//        ptr[2] = 3;
//
////        std::cout << "i: " << i <<std::endl;
//    }
    
    for (int i = 1; i<= 10000000; i++) {
        auto arp = std::shared_ptr <int32_t>(new int32_t[3]);
        int32_t* ptr = arp.get();
        ptr[0] = 1;
        ptr[1] = 2;
        ptr[2] = 3;
        
        //        std::cout << "i: " << i <<std::endl;
    }
    system("pause");
#else

    std::cout << "manual!\n";
    
    //used memory size is
    for (int i = 1; i <= 10000000; i++)
    {
        int32_t *ptr = new int32_t[3];
        ptr[0] = 1;
        ptr[1] = 2;
        ptr[2] = 3;
        delete []ptr;     //假设忘记了释放内存
    }
    system("pause");
    
#endif

    return 0;
}
